package com.luozongyao.eduUcenter.controller;

import com.google.gson.Gson;
import com.luozongyao.commonutils.JwtUtils;
import com.luozongyao.eduUcenter.entity.UcenterMember;
import com.luozongyao.eduUcenter.service.UcenterMemberService;
import com.luozongyao.eduUcenter.utlis.ConstantPropertiesUtil;
import com.luozongyao.eduUcenter.utlis.HttpClientUtils;
import com.luozongyao.servicebase.config.exceptionHandler.lzyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @program: guli_parent
 * @description:
 * @author: Zongyao Luo
 * @create: 2021-08-22 11:10
 **/
@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    //2获取扫描人信息，添加数据  callback是固定的，不能乱写跟配置文件一样
    @GetMapping("callback")
    public String callback(String code ,String state){
        //得到授权临时票据code
//        System.out.println("code:"+code);
//        System.out.println("state:"+state);
        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //请求这个拼接好的地址，得到返回两个值 accsess_token和 openid
            // 使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //accessToken的值
            // {"access_token":"48_qDEXRt3vCGEx_UQRR_YUP2k_XxwiJQrV8NL5AD68l3dyRXv6PmpyGrM1e4SES57i1N7DSrvnJjWSow9PP8_t6caPnUqO2JCeDoupKmnoGDg",
            //"expires_in":7200,
            //"refresh_token":"48_bmWrrYZeMys_thbZMOsD95ZU0RbnEhDMdHj1ac-9AULt58rr1LsKgWKHw9JgD1EdRy3ng5c60ChY2EiXSrYgVYj53pjbbZ0ADSmkNvuvwOU",
            //"openid":"o3_SC53E93kdwmNruMqqi-JttZns",
            //"scope":"snsapi_login",
            //"unionid":"oWgGz1AIMWxxo3Tf4y7JR1dcWsiA"}
            //从accessTokenInfo字符串获取出来两个值 accsess_token 和 openid
            // 把accessTokenInfo字符串转换map集合，根据map里面key获取对应值
            // 使用json转换工具Gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String openid = (String) mapAccessToken.get("openid");
            String access_token = (String) mapAccessToken.get("access_token");
            //查询数据库当前用用户是否曾经使用过微信登录
            UcenterMember member = memberService.getUserByOpenId(openid);
            if (member == null){  //没有就添加
                //3. 拿着得到accsess_token和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfo_url = String.format(baseUserInfoUrl,
                        access_token,
                        openid);
                //发送请求
                String userInfo = HttpClientUtils.get(userInfo_url);
                System.out.println(userInfo);//{"openid":"o3_SC53E93kdwmNruMqqi-JttZns","nickname":"Lzy","sex":1,"language":"zh_HK","city":"Jieyang","province":"Guangdong","country":"CN","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/uJicQ1R27PuzsicnkIyIF5LGeO5V5WhtQLpzSlD2klyWCzNRXXTkOlsK4hK9ice01KKpXZFCACDwgjKQxvdhaoTNQ\/132","privilege":[],"unionid":"oWgGz1AIMWxxo3Tf4y7JR1dcWsiA"}
                //获取返回userinfo字符串扫描人信息 解析json
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname= (String) userInfoMap.get("nickname"); //昵称
                String headimgurl= (String) userInfoMap.get("headimgurl"); //头像
                //把扫描人信息添加数据库里面
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                member.setOpenid(openid);
                memberService.save(member);

            }
            //使用jwt根据member对象生成token字符串 放入id和昵称
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //存入cookie
            //CookieUtils.setCookie(request, response, "guli_jwt_token", token);
            //因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写
            //最后返回到首页
            return "redirect:http://localhost:3000?token="+jwtToken;

        } catch (Exception e) {
            throw  new lzyException(20001,"登录失败");
        }

    }

    //1.生成微信二维码
    @GetMapping("login")
    public String getQRCode(){
        // 微信开放平台授权baseUrl
        String base_url = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //对redirect_url进行URLEncoder编码
        String redirectUrl=ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (Exception e) {
            throw new lzyException(20001,"地址编码失败");
        }
        String QRCodeUrl = String.format(
                base_url,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "lzy");

        return "redirect:"+QRCodeUrl;
    }

}
